package com.atguigu.gateway.filter;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.time.LocalDateTime;
import java.util.LinkedHashSet;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.*;

/**
 * @author Fxz
 * @version 1.0
 * @date 2021-12-07 10:18
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class FxzGatewayRequestFilter implements GlobalFilter {

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		// 日志打印
		printLog(exchange);
		return chain.filter(exchange);
	}

	private void printLog(ServerWebExchange exchange) {
		URI url = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
		Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
		LinkedHashSet<URI> uris = exchange.getAttribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
		URI originUri = null;
		if (uris != null) {
			originUri = uris.stream().findFirst().orElse(null);
		}
		if (url != null && route != null && originUri != null) {
			log.info("转发请求：{}://{}{} --> 目标服务：{}，目标地址：{}://{}{}，转发时间：{}", originUri.getScheme(),
					originUri.getAuthority(), originUri.getPath(), route.getId(), url.getScheme(), url.getAuthority(),
					url.getPath(), LocalDateTime.now());
		}
	}

}
